package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.homeservicemanagementsystem.entity.ImageVo;
import com.heima.homeservicemanagementsystem.entity.ServiceServicedetail;
import com.heima.homeservicemanagementsystem.entity.SysRole;
import com.heima.homeservicemanagementsystem.entity.dto.Option;
import com.heima.homeservicemanagementsystem.service.ServiceServicedetailService;
import com.heima.homeservicemanagementsystem.utils.FileUtils;
import io.micrometer.common.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import com.heima.homeservicemanagementsystem.entity.ServiceClassification;
import com.heima.homeservicemanagementsystem.service.ServiceClassificationService;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

import static cn.dev33.satoken.SaManager.log;

/**
 * 服务分类;(service_classification)表控制层
 *
 * @author : http://www.chiner.pro
 * @date : 2025-4-4
 */
@Slf4j
@Tag(name = "服务分类对象功能接口")
@RestController
@RequestMapping("/serviceClassification")
public class ServiceClassificationController {
    @Autowired
    private Environment environment;
    @Resource
    private ServiceClassificationService serviceClassificationService;

    @Operation(summary = "分页查询")
    @PostMapping("/page")
    @SaIgnore
    public Result<Page<ServiceClassification>> paginQuery(@RequestBody PageParams<ServiceClassification> pageParams) {
        //查询参数

        ServiceClassification params = pageParams.getParams();
        LambdaQueryWrapper<ServiceClassification> lqw = new LambdaQueryWrapper<>();

        lqw.eq(StringUtils.isNotBlank(params.getId()), ServiceClassification::getId, params.getId());
        lqw.eq(Objects.nonNull(params.getType()), ServiceClassification::getType, params.getType());


        lqw.like(StringUtils.isNotBlank(params.getFlName()), ServiceClassification::getFlName, params.getFlName());


        lqw.eq(StringUtils.isNotBlank(params.getParentId()), ServiceClassification::getParentId, params.getParentId());
//        List<ServiceClassification> list = serviceClassificationService.list(lqw);
//        for (ServiceClassification classification : list) {
//            if (classification.getParentId() != null) {
//                ServiceClassification parent = serviceClassificationService.getById(classification.getParentId());
//                classification.setParentName(parent);
//            }
//        }
        Page<ServiceClassification> page = serviceClassificationService.page(pageParams.getPage(), lqw);
        List<ServiceClassification> records = page.getRecords();
        for (ServiceClassification record : records) {
            if (record.getParentId() != null) {
                ServiceClassification parent = serviceClassificationService.getById(record.getParentId());
                record.setParentName(parent);
//
            }
        }
        page.setRecords(records);
        return Result.success(page);
    }

    @SaIgnore
    @Operation(summary = "手机分页查询")
    @PostMapping("/paginmdQuery")
    public Result paginmdQuery(@RequestBody PageParams<ServiceClassification> pageParams) {
        log.info("分页查询参数:{}", pageParams);
        QueryWrapper<ServiceClassification> lqw = new QueryWrapper<>();
        lqw.eq("type", 0);
        Page<ServiceClassification> page = serviceClassificationService.page(pageParams.getPage(), lqw);
        for (ServiceClassification record : page.getRecords()) {
            QueryWrapper<ServiceClassification> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", record.getId()).last("LIMIT 3");

            List<ServiceClassification> list = serviceClassificationService.list(wrapper);
            record.setChildren(list);
        }

        return Result.success(page);
    }

    @SaIgnore
    @Operation(summary = "服务分类查询")
    @PostMapping("/paginmdQueryfl")
    public Result paginmdQueryfl(@RequestBody PageParams<ServiceClassification> pageParams) {
        log.info("分页查询参数:{}", pageParams);
        QueryWrapper<ServiceClassification> lqw = new QueryWrapper<>();
        lqw.eq("type", 0);
        Page<ServiceClassification> page = serviceClassificationService.page(pageParams.getPage(), lqw);
        for (ServiceClassification record : page.getRecords()) {
            QueryWrapper<ServiceClassification> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", record.getId());

            List<ServiceClassification> list = serviceClassificationService.list(wrapper);
            record.setChildren(list);
        }

        return Result.success(page);
    }

    @SaIgnore
    @Operation(summary = "服务分类查询2")
    @PostMapping("/paginmdQueryfl2")
    public Result paginmdQueryfl2() {

        QueryWrapper<ServiceClassification> lqw = new QueryWrapper<>();
        lqw.eq("type", 0);
        List<ServiceClassification> list1 = serviceClassificationService.list(lqw);
        for (ServiceClassification record : list1) {
            QueryWrapper<ServiceClassification> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", record.getId());

            List<ServiceClassification> list = serviceClassificationService.list(wrapper);
            record.setChildren(list);
        }

        return Result.success(list1);
    }

    @PostMapping("/upload")
    @Operation(summary = "后端分类图片上传")
    public Result<ArrayList<ImageVo>> upload(@RequestParam("file") MultipartFile file) {
        log.info("文件:{}", file);
        String port = environment.getProperty("server.port");
//        System.out.println("Server port: " + port);
        String upload = FileUtils.upload(file);

        ImageVo imageVo = new ImageVo();
        String randomId = UUID.randomUUID().toString();
        imageVo.setUid(randomId);
        imageVo.setName(upload);
        imageVo.setStatus("done");
        imageVo.setUrl("http://127.0.0.1:" + port + "/upload/" + upload);
        ArrayList<ImageVo> objects = new ArrayList<>();
        objects.add(imageVo);

        return Result.success("文件上传成功！", objects);


    }

    @Operation(summary = "所有搜索")
    @GetMapping("/list")
    public Result searchQuery() {
        List<ServiceClassification> list = serviceClassificationService.list();
        for (ServiceClassification classification : list) {
            if (classification.getParentId() != null) {
                ServiceClassification parent = serviceClassificationService.getById(classification.getParentId());
                classification.setParentName(parent);
            }
        }
        return Result.success(list);
    }

    @Operation(summary = "有条件的搜索")
    @PostMapping("/tjSearch")
    public Result Query(@RequestBody ServiceClassification serviceClassification) {
        LambdaQueryWrapper<ServiceClassification> lqw = new LambdaQueryWrapper<>();
        log.info("前端信息：{}", serviceClassification);

        lqw.eq(serviceClassification.getId() != null, ServiceClassification::getId, serviceClassification.getId());


        lqw.eq(serviceClassification.getType() != null, ServiceClassification::getType, serviceClassification.getType());


        lqw.like(serviceClassification.getFlName() != null, ServiceClassification::getFlName, serviceClassification.getFlName());


        lqw.eq(serviceClassification.getParentId() != null, ServiceClassification::getParentId, serviceClassification.getParentId());
        List<ServiceClassification> list = serviceClassificationService.list(lqw);
        for (ServiceClassification classification : list) {
            if (classification.getParentId() != null) {
                ServiceClassification parent = serviceClassificationService.getById(classification.getParentId());
                classification.setParentName(parent);
            }
        }

        return Result.success(list);
    }

    /**
     * 新增数据
     *
     * @param serviceClassification 实例对象
     * @return 实例对象
     */
    @Operation(summary = "新增数据")
    @PostMapping("/insert")
    public Result<Boolean> insert(@RequestBody ServiceClassification serviceClassification) {

        if (serviceClassificationService.save(serviceClassification)) {
            return Result.success();
        }
        return Result.error();
    }

    @SaIgnore
    @Operation(summary = "服务父级下拉列表")
    @GetMapping("/serviceParent")
    public Result<List<Option>> roleOptions() {
        //查询参数

        QueryWrapper<ServiceClassification> lqw = new QueryWrapper<>();
        lqw.select("fl_name AS label", "id AS value");
        lqw.eq("type", 0);
        List<Map<String, Object>> maps = serviceClassificationService.listMaps(lqw);

        List<Option> optionals = BeanUtil.copyToList(maps, Option.class);
        return Result.success(optionals);
    }

    @SaIgnore
    @Operation(summary = "服务子级下拉列表")
    @GetMapping("/serviceChild")
    public Result<List<Option>> roleOptionschildren() {
        //查询参数

        QueryWrapper<ServiceClassification> lqw = new QueryWrapper<>();
        lqw.select("fl_name AS label", "id AS value");
        lqw.eq("type", 1);
        List<Map<String, Object>> maps = serviceClassificationService.listMaps(lqw);

        List<Option> optionals = BeanUtil.copyToList(maps, Option.class);
        return Result.success(optionals);
    }

    /**
     * 更新数据
     *
     * @param serviceClassification 实例对象
     * @return 实例对象
     */
    @Operation(summary = "更新数据")
    @PutMapping("update")
    public Result<Boolean> update(@RequestBody ServiceClassification serviceClassification) {
        if (serviceClassificationService.updateById(serviceClassification)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Operation(summary = "通过主键删除数据",
            parameters = {
                    @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
            })
    @GetMapping("/delete/{id}")
    public Result<Boolean> deleteById(@PathVariable String id) {

        if (serviceClassificationService.removeById(id)) {

            return Result.success();
        }
        return Result.error();
    }

    @Operation(summary = "多id删除数据")
    @PostMapping("/delete")
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
        log.info("前端信息：{}", id);
        if (serviceClassificationService.removeByIds(id)) {
            ServiceServicedetailService serviceServicedetailService = SpringUtil.getBean(ServiceServicedetailService.class);
            QueryWrapper<ServiceServicedetail> detailId = new QueryWrapper<ServiceServicedetail>().eq("serviceId", id.get(0));
            serviceServicedetailService.remove(detailId);
            return Result.success();
        }
        return Result.error();
    }
}